// 患者
// 导入数据库查询方法
const { getAll, update } = require('../../utils/dbTools');
const { isValidator } = require('../../utils/util');

// 患者数据表名称
const tableName = 'patient';

// 根据医生id查询患者列表
const patientList = async (req, res) => {
    const output = {
        code: 200,
        msg: "操作成功"
    }
    const { doctorid, page, size } = req.query;

    const params = {};
    if (page && size) {
        params.page = page;
        params.size = size;
    }
    if (doctorid) {
        params.doctorid = doctorid;
    }
    const result = await getAll(tableName, params);
    if (!result) {
        output.code = 500;
        output.msg = "操作失败";
        return res.send(output);
    }
    output.data = result;
    res.send(output);
}

// 更新患者信息
// 更新信息
const patientUpdate = async (req, res) => {
    const output = {
        code: 200,
        msg: "操作成功"
    }
    const { id, phone } = req.body;
    if (!id) {
        output.code = 500;
        output.msg = "参数错误:缺少id"
        return res.send(output);
    }
    // 要更新的信息
    const payload = { ...req.body }
    // 如果提交了手机号码
    if (phone) {
        // 检查手机号码是否重复
        if (!await isValidator(tableName, 'phone', phone)) {
            output.code = 500;
            output.msg = "手机号码已存在"
            return res.send(output);
        }
    }

    delete payload.id
    await update(id, payload, tableName,);
    res.send(output);
}


module.exports = {
    patientList, patientUpdate
}